﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SQLite;
using DialogsEditor.DAO;
using Microsoft.VisualBasic.PowerPacks;

namespace DialogsEditor
{
    public partial class Form1 : Form
    {
        private LoadDialogForm loadForm;

        public static bool IsLinking = false;
        public static DialogEntity Selected = null;

        public static DialogEntity CurrentProject = null;
        public static List<DialogEntity> CurrentDialogs = new List<DialogEntity>();
        public static List<Line> CurrentLinks = new List<Line>();
        public static List<DialogEntity> LoadDialogsEntity = new List<DialogEntity>();

        public static Pen PenUnselect { get; set; }
        public static Pen PenSelect { get; set; }

        public static ShapeContainer ContainerShape { get; set; }

        public static LineShape CurrentLink { get; set; }

        public Timer _timer;

        public static Point CursorPoint;

        public Form1()
        {
            InitializeComponent();
            
            PenUnselect = new Pen(Brushes.Black, 5);
            PenUnselect.StartCap = System.Drawing.Drawing2D.LineCap.RoundAnchor;
            PenUnselect.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;

            PenSelect = new Pen(Brushes.Yellow, 5);
            PenSelect.StartCap = System.Drawing.Drawing2D.LineCap.RoundAnchor;
            PenSelect.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;

            ContainerShape = MyContainer();
            CurrentLink = MyLineShape();

            _timer = new Timer();
            _timer.Interval = 100;
            _timer.Tick += _timer_Tick;
            _timer.Start();
        }

        void _timer_Tick(object sender, EventArgs e)
        {
            Refresh();

            if (IsLinking)
            {
                foreach (DialogEntity d in CurrentDialogs)
                {
                    if (!d.IsSelected) continue;

                    if (d.idNextDialog <= 0)
                        Selected = d;
                }
            }
        }

        public static LineShape MyLineShape()
        {
            LineShape sc = new LineShape();
            sc.BorderWidth = 5;
            return sc;
        }

        private ShapeContainer MyContainer()
        {
            ShapeContainer sc = new ShapeContainer();
            sc.Top = 20;
            return sc;
        }


        #region CLICK
        private void Exit_Click(object sender, EventArgs e)
        {
            _timer.Tick -= _timer_Tick;
            _timer.Stop();
            Close();
        }

        private void NewDialogScreen_Click(object sender, EventArgs e)
        {
            if (CurrentProject == null)
            {
                MessageBox.Show("Selecione um projeto ou então crie um novo projeto");
                return;
            }
            NewDialogForm newDialogForm = new NewDialogForm(this, NewDialogForm.DialogType.DIALOG);
            newDialogForm.Show();
        }

        private void NewDialog_Click(object sender, EventArgs e)
        {
            NewDialogForm newDialogForm = new NewDialogForm(this, NewDialogForm.DialogType.PROJECT);
            newDialogForm.Show();
            IsLinking = false;
            toolStripMenuItem9.Text = "Open Link Creator";
        }

        private void Load_Click(object sender, EventArgs e)
        {
            if (loadForm == null)
                loadForm = new LoadDialogForm(this);
            loadForm.ShowLoadDialogs();
            IsLinking = false;
            toolStripMenuItem9.Text = "Open Link Creator";
        }

        private void AddLink(object sender, EventArgs e)
        {
            if (!IsLinking)
            {
                foreach (DialogEntity d in CurrentDialogs)
                {
                    d.SetDraggable(false);
                }
                IsLinking = true;
                toolStripMenuItem9.Text = "Close Link Creator";
            }
            else
            {
                foreach (DialogEntity d in CurrentDialogs)
                {
                    d.SetDraggable(true);
                }
                IsLinking = false;
                toolStripMenuItem9.Text = "Open Link Creator";
            }
        }

        private void Save_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Deseja salvar o projeto atual?", "", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                //salvar geral que não está salvo e dar update em que já está salvo
                foreach (DialogEntity d in CurrentDialogs)
                {
                    if (d.GetID() <= 0)
                    {
                        DialogEditorDAO.SaveDialog(d);
                        using (SQLiteConnection conn = ConnFactory.getInstancia().GetConnDialog())
                        {
                            d.SetID(DialogEditorDAO.GetId(conn, "select id from dialog WHERE", "title", d.title.Text));
                        }
                    }
                    else { DialogEditorDAO.UpdateDialog(d); }
                }

                MessageBox.Show("Projeto salvo!");
            }
        }

        private void Delete_Click(object sender, EventArgs e)
        {
            if (CurrentProject == null)
            {
                MessageBox.Show("Selecione um projeto ou então crie um novo projeto");
                return;
            }

            DialogEntity selected = null;
            foreach (DialogEntity d in CurrentDialogs)
            {
                if (d.IsSelected)
                {
                    selected = d;
                    break;
                }
            }
            //Apagar um dialogo isolado
            if (selected != null)
            {
                if (MessageBox.Show("Você realmente deseja excluir o dialogo selecionado?", "", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    //Removendo o dialogo selecionado
                    //if (Selected.GetID() > 0)
                    //    UtilsDAO.DeleteDialog(Selected);

                    CurrentDialogs.Remove(selected);
                    this.Controls.Remove(selected);
                    //Apagando as ligações
                    foreach (DialogEntity d in CurrentDialogs)
                    {
                        if (d.idNextDialog == selected.GetID())
                            d.idNextDialog = 0;
                    }
                    List<Line> trash = new List<Line>();
                    foreach (Line link in CurrentLinks)
                    {
                        if (link.Source == selected || link.Destination == selected)
                        {
                            link.shape.Visible = false;
                            trash.Add(link);
                        }
                    }

                    foreach (Line link in trash)
                    {
                        CurrentLinks.Remove(link);
                        ContainerShape.Shapes.Remove(link.shape);
                    }


                    MessageBox.Show("Diálogo excluído");
                }
            }
            else
            {
                Line lineSelected = null;
                foreach (Line link in CurrentLinks)
                {
                    if (link.IsSelected)
                    {
                        lineSelected = link;
                        break;
                    }
                }

                if (lineSelected != null)
                {
                    if (MessageBox.Show("Você realmente deseja excluir a ligação selecionada?", "", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    {
                        lineSelected.Source.idNextDialog = 0;
                        lineSelected.shape.Visible = false;

                        CurrentLinks.Remove(lineSelected);
                        ContainerShape.Shapes.Remove(lineSelected.shape);

                        lineSelected = null;

                        MessageBox.Show("Link excluído");
                    }
                }
                else
                {
                    if (MessageBox.Show("Você realmente deseja excluir o projeto atual?", "", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    {
                        DialogEditorDAO.DeleteProjectDialog(CurrentProject);
                        ClearControlDialog();
                        CurrentProject = null;
                        ClearControlDialog();
                        MessageBox.Show("Projeto excluído");
                    }
                }
            }
        }

        #endregion

        public void ClearControlDialog()
        {
            foreach (DialogEntity d in CurrentDialogs)
            {
                if (this.Controls.Contains(d))
                    this.Controls.Remove(d);
            }
            CurrentDialogs.Clear();

            /*foreach (Line line in CurrentLinks)
            {
                if (this.Controls.Contains(line))
                    this.Controls.Remove(line);
            }*/
            foreach (Line line in CurrentLinks)
            {
                if (ContainerShape.Shapes.Contains(line.shape))
                    ContainerShape.Shapes.Remove(line.shape);
            }
            this.Controls.Remove(ContainerShape);
            CurrentLinks.Clear();
        }

        public void ShowFormDialogs()
        {
            
            /*foreach (Line line in CurrentLinks)
            {
                if (!this.Controls.Contains(line))
                    this.Controls.Add(line);
            }*/
            foreach (Line line in CurrentLinks)
            {
                line.shape.Parent = ContainerShape;
                line.shape.Refresh();
            }
            this.Controls.Add(ContainerShape);

            foreach (DialogEntity d in CurrentDialogs)
            {
                if (!this.Controls.Contains(d))
                    this.Controls.Add(d);
            }
            //Container.Refresh();
            //Invalidate();
            Refresh();
        }


        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);
            Selected = null;
            foreach (DialogEntity d in CurrentDialogs)
            {
                d.IsSelected = false;
                d.Refresh();
            }
            foreach (Line line in CurrentLinks)
            {
                line.IsSelected = false;
                line.RemoveSelection();
                line.Refresh();
            }

            if (IsLinking)
            {
                ClearCurrentLink();
            }

        }

        /*protected override void OnMouseUp(MouseEventArgs e)
        {
            base.OnMouseUp(e);
            //Selected = null;
            //ClearCurrentLink();
        }*/

        public static void ClearCurrentLink()
        {
            if (ContainerShape.Shapes.Contains(CurrentLink))
                ContainerShape.Shapes.Remove(CurrentLink);
            CurrentLink = null;
        }

        public static void DrawLinks()
        {
            foreach (Line line in CurrentLinks)
            {
                if (!ContainerShape.Shapes.Contains(line.shape))
                    ContainerShape.Shapes.Add(line.shape);
                line.PaintLine();
            }
        }

        private void ManageDialogs(object sender, PaintEventArgs e)
        {
            if (CurrentProject != null)
                mpos.Text = "Título do Projeto: " + CurrentProject.title.Text;
            
            DrawLinks();

            if (!IsLinking || Selected == null || CurrentLink == null) return;

            CurrentLink.Visible = true;
            CurrentLink.X1 = Selected.Position.X;
            CurrentLink.Y1 = Selected.Position.Y;
            CurrentLink.X2 = PointToClient(Cursor.Position).X;
            CurrentLink.Y2 = PointToClient(Cursor.Position).Y;
            
            //e.Graphics.DrawLine(PenUnselect, Selected.Location, this.PointToClient(Cursor.Position));
            //Container.Refresh();
        }

        private void bDAdminToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //DatabaseForm bdform = new DatabaseForm();
            //bdform.Show();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            Form1.LoadDialogsEntity.Clear();
            base.OnClosing(e);
        }

    }

    public class Utils
    {
        public static void UnselectingAllDialogs()
        {
            foreach (DialogEntity d in Form1.CurrentDialogs)
            {
                d.IsSelected = false;
                d.Refresh();
            }
        }

        public static void UnselectingAllLinks()
        {
            foreach (Line d in Form1.CurrentLinks)
            {
                d.IsSelected = false;
                d.Refresh();
                d.RemoveSelection();
            }
        }

    }
}
